package com.bootdo.per.controller;

import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.intThat;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.per.config.PerConstant;
import com.bootdo.per.domain.TeamDO;
import com.bootdo.per.domain.TeamModel;
import com.bootdo.per.service.ManagerService;
import com.bootdo.per.service.TeamService;
import com.bootdo.per.service.WeightService;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.DeptService;
import com.bootdo.system.service.RoleService;


import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.exception.BDException;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 
 * 
 * @author readke
 * @email 1992lcg@163.com
 * @date 2018-06-05 17:51:30
 */
 
@Controller
@RequestMapping("/per/team")
public class TeamController extends BaseController{
	@Autowired
	private TeamService teamService;
	@Autowired 
	private DeptService deptService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private WeightService weightService;
	@Autowired
	Environment e;
	
	@GetMapping()
	@RequiresPermissions("per:team:team")
	String Team(Model model){
		String status = managerService.list(null).get(0).getStatus();
		model.addAttribute("mStatus", status);
	    return "per/team/team";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("per:team:team")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
        query.put("scoreUserId", getUserId());
		List<TeamDO> teamList = teamService.listByGroup(query);
		int total = teamService.listByGroupCount(query);
		PageUtils pageUtils = new PageUtils(teamList, total);
		return pageUtils;
	}
	
	public List<Object> reportList(Map<String,Object> map){
		if(isManager()){
			//查询所有的团队
		}else if(hasManagerTeam()){
			//查询分管的团队
		}else {
			//当前用户评价的团队
		}
		map.put("scoreUserId", getUserId());
		teamService.reportList(map);
		List<TeamDO> teamList = teamService.listByGroup(map);
		return null;
	}
	
	@GetMapping("/score")
	@RequiresPermissions("per:team:score")
	String score(Model model){
		Map<String,Object> map = getScoreMonth();
		model.addAttribute(Constant.TYPE_MONTH, map.get(Constant.TYPE_MONTH));
		model.addAttribute(Constant.TYPE_YEAR, map.get(Constant.TYPE_YEAR));
		
		//考核管理关闭
		if(!isOn()){
			throw new BDException("当前考核管理已经关闭，不能进行评分操作");
		}
		//已经考核过则跳到修改页面
		if(isScore(map)){
			return "redirect:/per/team/edit";
		}
	
		List<DeptDO> deptList = null;
		UserDO user =  getUser();
		if(isManagerHouse(user.getDeptId())){
			deptList = teamService.listByManager(user.getDeptId());
			model.addAttribute("deptList", deptList);
			return "per/team/manager_score";
		}else{
			deptList = teamService.listBySupervisor(user.getDeptId());
			model.addAttribute("deptList", deptList);
			return "per/team/supervisor_score";
		}
		
	    
	}
	@ResponseBody
	@PostMapping("/saveScoreByMan")
	@RequiresPermissions("per:team:score")
	public R saveScoreByMan( TeamModel teamModel) throws IllegalAccessException, InvocationTargetException{
		Map<String ,Object> map = getScoreMonth();
		
		UserDO user = getUser();
		//总经理权重
		BigDecimal manWt = weightService.getWeight(PerConstant.MAN_ROLE_TYPE);
		//分管总权重
		BigDecimal mainManWt = weightService.getWeight(PerConstant.MAIN_MAN_ROLE_TYPE);
		//其他总权重(权重除以其他总人数)
		BigDecimal othManWt = weightService.getWeight(PerConstant.OTH_MAN_ROLE_TYPE);
		//获取其他总角色人数
		int othManCount = roleService.getCountByRoleName(e.getProperty("othManName"));
		BigDecimal oCount = new BigDecimal(othManCount);
		othManWt = othManWt.divide(oCount, 6, BigDecimal.ROUND_HALF_DOWN);
		
		List<TeamDO> list = teamModel.getList();
		if(isManager()){//方法待实现
			//总经理
			//list中所有人的权重为manWt
			for(TeamDO team: list){
				team.setMonth((Integer)map.get(Constant.TYPE_MONTH));
				team.setYear((Integer)map.get(Constant.TYPE_YEAR));
				team.setQuarter((Integer)map.get(Constant.TYPE_QUARTER));
				team.setScoreUserWeight(manWt);
				team.setScoreUser(getUsername());
				team.setScoreUserId(getUserId());
				team.setScoreTime(new Date());
			}
			//总经理分管团队
			if(hasManagerTeam()){
				List<String> deptIds = user.getmDeptIds();
				List<TeamDO> l = new ArrayList<>();
				for(TeamDO team: list){
					for(String deptId : deptIds){
						TeamDO t = new TeamDO();
						if(team.getDeptId().equals(deptId)){
							BeanUtils.copyProperties(t, team);
							t.setScoreUserWeight(mainManWt);
							l.add(t);
						}
						
					}
				}
				list.addAll(l);
			}
		}else{
			//非总经理
			for(TeamDO team: list){
				team.setMonth((Integer)map.get(Constant.TYPE_MONTH));
				team.setYear((Integer)map.get(Constant.TYPE_YEAR));
				team.setQuarter((Integer)map.get(Constant.TYPE_QUARTER));
				team.setScoreUserWeight(othManWt);
				team.setScoreUser(getUsername());
				team.setScoreUserId(getUserId());
				team.setScoreTime(new Date());
			}
			//非总经理分管团队
			if(hasManagerTeam()){//方法待实现
				List<String> deptIds = user.getmDeptIds();
				for(TeamDO team: list){
					for(String deptId : deptIds){
						if(team.getDeptId().equals(deptId)){
							team.setScoreUserWeight(mainManWt);
						}
						
					}
				}
			}
		}
		
		if(teamService.saveList(list)>0){
			return R.ok();
		}
		return R.error();
		
	}
	@ResponseBody
	@PostMapping("/saveScoreByTeam")
	@RequiresPermissions("per:team:score")
	public R saveScoreByTeam( TeamModel teamModel) throws IllegalAccessException, InvocationTargetException{
		Map<String ,Object> map = getScoreMonth();
		UserDO user = getUser();
		//规划分析主管权重
		BigDecimal projectWt = weightService.getWeight(PerConstant.PROJECT_SUP_ROLE_TYPE);
		//主管权重(主管权重/(主管人数-1))
		BigDecimal supervisorWt = weightService.getWeight(PerConstant.SUP_ROLE_TYPE);
		
		//获取主管角色人数
		int supervisorCount = roleService.getCountByRoleName(e.getProperty("supName"));
		BigDecimal sCount = new BigDecimal(supervisorCount);
		supervisorWt = supervisorWt.divide(sCount, 6, BigDecimal.ROUND_HALF_DOWN);
		
		List<TeamDO> list = teamModel.getList();
		if(isPlanner()){//方法待实现
			//评价所有团队使用规划主管权重
			//list中所有人的权重为manWt
			List<TeamDO> l = new ArrayList<>();
			for(TeamDO team: list){
				team.setMonth((Integer)map.get(Constant.TYPE_MONTH));
				team.setYear((Integer)map.get(Constant.TYPE_YEAR));
				team.setQuarter((Integer)map.get(Constant.TYPE_QUARTER));
				team.setScoreUserWeight(projectWt);
				team.setScoreUser(getUsername());
				team.setScoreUserId(getUserId());
				team.setScoreTime(new Date());
				log.info("team deptId:{} , user deptId :{}",team.getDeptId(),user.getDeptId());
				if(team.getDeptId().equals(user.getDeptId())){
					//评价规划分析团队时候使用普通主管权重
					TeamDO t = new TeamDO();
					BeanUtils.copyProperties(t, team);
					t.setScoreUserWeight(supervisorWt);
					l.add(t);
				}
			}
			list.addAll(l);
			
		}else{
			//一般主管
			for(TeamDO team: list){
				team.setMonth((Integer)map.get(Constant.TYPE_MONTH));
				team.setYear((Integer)map.get(Constant.TYPE_YEAR));
				team.setQuarter((Integer)map.get(Constant.TYPE_QUARTER));
				team.setScoreUserWeight(supervisorWt);
				team.setScoreUser(getUsername());
				team.setScoreUserId(getUserId());
				team.setScoreTime(new Date());
			}
			
		}
		
		if(teamService.saveList(list)>0){
			return R.ok();
		}
		return R.error();
		
	}
	/**
	 * 当前用户是否是规划分析团队主管
	 * @return
	 */
	private boolean isPlanner() {
		Map<String,Object> map = new HashMap<>();
		map.put("name", e.getProperty("planName"));
		map.put("deptId", getUser().getDeptId());
		List<DeptDO> list = deptService.list(map);
		return list!=null && list.size()>0;
	}

	/**
	 * 当前用户是否有分管团队
	 * @return
	 */
	private boolean hasManagerTeam() {
		String mDeptId = getUser().getManageDeptId();
		return mDeptId != null && !mDeptId.equals("");
	}

	/**
	 * 当前用户是否是总经理
	 * @return
	 */
	private boolean isManager() {
		Map<String,Object> map = new HashMap<>();
		map.put("userId", getUserId());
		map.put("roleName", e.getProperty("manName"));
		List<Map<String,Object>> list = roleService.getRole(map);
		return list!=null && list.size()>0;
	}
	
	/**
	 * 评分查看
	 * @param map
	 * @param model
	 * @return
	 */
	@GetMapping("/view")
	@RequiresPermissions("per:team:view")
	String view(@RequestParam Map<String,Object> map,Model model){
		map.put("scoreUserId", getUserId());
		map.put("sort", "score");
		map.put("order", "desc");
		model.addAttribute("teamList", teamService.list(map));
		model.addAttribute("map", map);
		
		if(isManagerHouse(getUser().getDeptId())){
			return "per/team/manager_score_view";
		}else{
			return "per/team/supervisor_score_view";
		}
	}
	
	/**
	 * 编辑考核成绩
	 * @param model
	 * @return
	 */
	@GetMapping("/edit")
	@RequiresPermissions("per:team:score")
	String edit(Model model){
		Map<String,Object> map = getScoreMonth();
		map.put("scoreUserId", getUserId());
		map.put("sort", "score");
		map.put("order", "desc");
		model.addAttribute("teamList", teamService.list(map));
		model.addAttribute("map", map);
		
		if(isManagerHouse(getUser().getDeptId())){
			return "per/team/manager_score_edit";
		}else{
			return "per/team/supervisor_score_edit";
		}
	}
	/**
	 * 修改考核成绩
	 * @param teamModel
	 * @return
	 */
	@ResponseBody
	@PostMapping("/updateScore")
	@RequiresPermissions("per:team:score")
	public R updateScore( TeamModel teamModel){

		List<TeamDO> list = teamModel.getList();
		for(TeamDO team: list){
			team.setModiTime(new Date());
			team.setModiUser(getUsername());
			team.setModiUserId(getUserId());
		}
		if(teamService.updateList(list)>0){
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 本月是否已经考核
	 * @return
	 */
	@ResponseBody
	@PostMapping("/isScore")
	@RequiresPermissions("per:team:score")
	public R isScore(){

		Map<String ,Object> map = getScoreMonth();
		map.put("scoreUserId",getUserId());
		if(teamService.count(map)>0){
			return R.error();
		}
		return R.ok();
	}
	
	/**
	 * 考评是否已经打开
	 * @return
	 */
	public boolean isOn(){
		String status = managerService.list(null).get(0).getStatus();
		return status.equals(Constant.SCORE_MANAGE_ON);
	}
	/**
	 * 该月是否已经考评
	 * @param year
	 * @param month
	 * @return
	 */
	public boolean isScore(Map<String,Object> scoreMonthMap){
		scoreMonthMap.put("scoreUserId",getUserId());
		if(teamService.count(scoreMonthMap)>0){
			return true;
		}
		return false;
	}
	/**
	 * 当前用户是否是总经理室成员
	 * @param id
	 * @return
	 */
	public boolean isManagerHouse(Long id){
		DeptDO dept = deptService.get(id);
		if("总经理室".equals(dept.getName())){
			return true;
		}
		return false;
	}
	
	/**
	 * 获取评分月
	 * @return
	 */
	public  Map<String ,Object>  getScoreMonth(){
		Map<String ,Object> map = new HashMap<String ,Object>();
		
		Integer year = DateUtils.getYear();
		Integer month = DateUtils.getMonth();
		Integer quarter = 0;
		if(month == 1){
			month = 12;
			quarter = 4;
			year--;
		}else{
			month --;
			quarter = (month+2)/3;
		}
		map.put(Constant.TYPE_YEAR,year);
		map.put(Constant.TYPE_MONTH,month);
		map.put(Constant.TYPE_QUARTER,quarter);
		return map;
	}
}
